package com.CampusForum.community.controller;

import com.CampusForum.community.entity.Comment;
import com.CampusForum.community.entity.DiscussPost;
import com.CampusForum.community.entity.Page;
import com.CampusForum.community.entity.User;
import com.CampusForum.community.service.CommentService;
import com.CampusForum.community.service.DiscussPostService;
import com.CampusForum.community.service.UserService;
import com.CampusForum.community.util.CommunityConstant;
import com.CampusForum.community.util.CommunityUtil;
import com.CampusForum.community.util.HostHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;


@Controller
@Slf4j
@RequestMapping("/discuss")
public class DiscussPostController implements CommunityConstant {
    @Autowired
    private HostHolder hostHolder;
    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private CommentService commentService;
    @Autowired
    private UserService userService;
    /**
     * 上传帖子
     */
    @PostMapping("/add")
    @ResponseBody
    public String addDiscussPost(String title, String content) {
        User user = hostHolder.getUser();
        if (user == null) {
            return CommunityUtil.getJSONString(403, "未登录，上传错误");
        }
        if (StringUtils.isBlank(title) || StringUtils.isBlank(content)) {
            return CommunityUtil.getJSONString(1, "数据存在空值，无法存入");
        }
        DiscussPost discussPost = new DiscussPost();
        discussPost.setUserId(user.getId());
        discussPost.setTitle(title);
        discussPost.setContent(content);
        discussPost.setType(0);
        discussPost.setStatus(0);
        discussPost.setCreateTime(new Date());
        discussPost.setCommentCount(0);
        int count = discussPostService.addDiscussPost(discussPost);
        if (count == 0) {
            return CommunityUtil.getJSONString(1, "数据未存入");
        } else if (count == 1){
            return CommunityUtil.getJSONString(0, "上传成功");
        } else {
            log.error("未知原因，插入多条数据！！！");
        }

        return CommunityUtil.getJSONString(1, "上传异常");
    }

    /**
     * 展示帖子
     */
    @GetMapping("/detail/{discussPostId}")
    public String getDiscussPostById(@PathVariable("discussPostId") int discussPostId,
                                     Model model, Page page) {
        Map<String, Object> map = discussPostService.getDiscussPostById(discussPostId);
        User user = (User) map.get("user");
        DiscussPost post = (DiscussPost) map.get("post");
        if (user != null) {
            model.addAttribute("user", user);
        } else {
            log.error("用户为空");
        }
        if (post != null) {
            model.addAttribute("post", post);
        } else {
            log.error("帖子为空");
        }
        page.setLimit(5);
        page.setRows(post.getCommentCount());
        page.setPath("/discuss/detail/" + post.getId());
        // 获取评论
        List<Comment> commentList = commentService.getComments(ENTITY_TYPE_POST, post.getId()
                , page.getOffset(), page.getLimit());
        if (commentList == null) {
            // post评论为空
            return "/site/discuss-detail";
        }
        List<Map<String, Object>> commentVo = new ArrayList<>();

        // post评论不为空
        for (Comment comment : commentList) {
            Map<String, Object> commentMap = new HashMap<>();
            commentMap.put("comment", comment);
            User commentUser = userService.getUserById(comment.getUserId());
            commentMap.put("user", commentUser);
            // 获取回复
            List<Comment> replyList = commentService.getComments(ENTITY_TYPE_COMMENT, comment.getId(),
                    0, Integer.MAX_VALUE);
            List<Map<String, Object>> replyVo = new ArrayList<>();
            if (replyList != null) {
                for (Comment reply : replyList) {
                    Map<String, Object> replyMap = new HashMap<>();
                    replyMap.put("reply", reply);
                    replyMap.put("user", userService.getUserById(reply.getUserId()));
                    User target =  reply.getTargetId() == 0 ? null : userService.getUserById(
                            reply.getTargetId());
                    replyMap.put("target", target);
                    replyVo.add(replyMap);
                }
            }
            commentMap.put("replys", replyVo);
            int replyCount = commentService.getCommentCount(ENTITY_TYPE_COMMENT, comment.getId());
            commentMap.put("replyCount", replyCount);
            commentVo.add(commentMap);
        }

        model.addAttribute("comments", commentVo);
        return "/site/discuss-detail";
    }
}
